package dyy.zc.note.ui.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.bmob.v3.BmobBatch;
import cn.bmob.v3.datatype.BmobFile;
import dyy.zc.note.R;
import dyy.zc.note.application.MyApplication;
import dyy.zc.note.base.BaseActivity;
import dyy.zc.note.bean.Classify;
import dyy.zc.note.bean.NoteInfo;
import dyy.zc.note.bean.UserInfo;
import dyy.zc.note.listener.MyOnItemClickListener;
import dyy.zc.note.listener.OnItemClickListener;
import dyy.zc.note.ui.adapter.ClassifyAdapter;
import dyy.zc.note.ui.adapter.NoteAdapter;
import dyy.zc.note.utils.AppManager;
import dyy.zc.note.utils.BmobUtils;
import dyy.zc.note.utils.DBControl;
import dyy.zc.note.utils.DividerItemDecoration;
import dyy.zc.note.utils.ImageLoaderUtils;
import dyy.zc.note.utils.ImageUploadUtil;
import dyy.zc.note.utils.ImageUtil;
import dyy.zc.note.utils.StringUtils;
import dyy.zc.note.utils.ToastUtils;
import dyy.zc.note.views.ActionSheet;
import dyy.zc.note.views.CircleImageView;
import dyy.zc.note.views.EmptyView;
import dyy.zc.note.views.MyAlertDialog;
import dyy.zc.note.views.slidemenu.SlidingMenu;


/**
 * Created by zhouchuan on 2017/2/27.
 */

public class MainActivity extends BaseActivity implements View.OnClickListener,ActionSheet.OnSheetItemClickListener {
    private TextView title,count;
    private SlidingMenu slidingMenu;
    private CircleImageView head;
    private DBControl dbControl;
    private List<NoteInfo> list = new ArrayList<>();
    private int allCount = 0;
    private Classify classifyUser;
    private NoteAdapter adapter;
    private ClassifyAdapter classifyAdapter;
    private RecyclerView recyclerView,sild_recyclerView;
    private CircleImageView slidHead;
    private TextView name;
    private String[] items = {"拍照", "我的相册"};
    // 头像文件、上传头像的名称、本地图片uri
    private File imageFile;
    private Uri imageUri; // 图片路径
    //拍照、从相册选择、照片保存成功
    private final int TAKE_PHOTO = 1, CHOOSE_PHOTO = 2, SAVE_IMAGE_SUCCESS = 3;
    private BmobUtils bmobUtils;
    private List<BmobFile> ImgList = new ArrayList<>();
    private EmptyView emptyView;
    @Override
    protected void findViewByIDS() {
        emptyView = new EmptyView(this);
        head = findViewsById(R.id.head);
        title = (TextView) findViewById(R.id.top_tv_title);
        recyclerView = findViewsById(R.id.recyclerView);
        initSlidingMenu();
        count = findViewsById(R.id.count);
        slidHead = findViewsById(R.id.slide_head);
        name = findViewsById(R.id.sliding_name);
        sild_recyclerView = findViewsById(R.id.sild_recyclerView);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
        bind();

    }


    private void initData() {
        bmobUtils = new BmobUtils(this);
        dbControl = new DBControl(this);
        adapter = new NoteAdapter(this,list);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        DividerItemDecoration decoration = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL_LIST);
        decoration.setDivider(R.drawable.divider_shape);
        recyclerView.addItemDecoration(decoration);
//        dialog = ProgressDialog.show(this,null,"正在获取日记......");
        Log.e("sdf",loginuser+"");
        if (loginuser !=null){
            if (loginuser.getNewInfo().equals("1")){
                ImageLoaderUtils.initImage(MainActivity.this,loginuser.getHead().getFileUrl(),slidHead,R.mipmap.my_defalft_headpic);
                ImageLoaderUtils.initImage(MainActivity.this,loginuser.getHead().getFileUrl(),head,R.mipmap.my_defalft_headpic);
                name.setText(loginuser.getName());
            }
            bmobUtils.getNote(loginuser,list,1,handler);

        }else {

            dbControl.query(list);
            Collections.reverse(list);
            count.setText(""+list.size()+"");
            if (list.size() == 0||list==null){
                emptyView.setNotify("快点写点日记吧~~~");
            }else {
                emptyView.setEmptyViewGone();
            }
            adapter.setOnline(false);
            recyclerView.setAdapter(adapter);
//            dialog.dismiss();
        }

    }

    private void bind() {
        findViewsById(R.id.add).setOnClickListener(this);
        findViewsById(R.id.camera).setOnClickListener(this);
        findViewsById(R.id.personal).setOnClickListener(this);
        findViewsById(R.id.new_fenzu).setOnClickListener(this);
        findViewsById(R.id.mydinary).setOnClickListener(this);
        head.setOnClickListener(this);
        adapter.setOnItemClickListener(new MyOnItemClickListener() {
            @Override
            public void onItemClick(RelativeLayout rl, int position) {
                Intent intent = new Intent(MainActivity.this,WriteActivity.class);
                intent.putExtra("note",list.get(position));
                intent.putExtra("check",1);
                if (classifyUser != null){
                    if (classifyUser.getName()!=null){
                        intent.putExtra("hasClass",1);
                        intent.putExtra("classify", (Serializable) classifyUser.getName());
                    }
                }
                startActivityForResult(intent,123);
            }

            @Override
            public void onDeleteClick(ImageView delete, int position) {
                deleteDialog(list.get(position).getId(),list.get(position));
            }
        });
    }

    /**
     * 删除提示框
     * @param id
     * @param noteInfo
     */
    private void deleteDialog(final String id, final NoteInfo noteInfo) {
        MyAlertDialog logDialog = new MyAlertDialog(this);
        logDialog.builder()
                .setTitle("删除提示")
                .setMsg("是否要删除？")
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                })
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (loginuser == null){
                            dbControl.delete(id);
                            setNotOnlineList();
                        }else {
                            bmobUtils.deleteNoteInfo(noteInfo,666,handler);
                        }
                    }
                })
                .show();

    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.add://点击添加日记
//                startActivityForResult(new Intent(MainActivity.this,ChangeActivity.class),234 );
                intent = new Intent(MainActivity.this,WriteActivity.class);
                if (classifyUser != null){
                    if (classifyUser.getName()!=null){
                        intent.putExtra("hasClass",1);
                        intent.putExtra("classify", (Serializable) classifyUser.getName());
                    }
                }
//                intent.putExtra("add",1);//表示从点击加号按钮进入
                startActivityForResult(intent,123);
                break;
            case R.id.head://弹出侧滑菜单
                if (!slidingMenu.isMenuShowing()) {
                    slidingMenu.showMenu();
                }
                break;
            case R.id.camera://点击照相，然后添加日记
                loginuser = MyApplication.getInstance().readLoginUser();
                if (loginuser==null){
                    ToastUtils.shortToast(MainActivity.this,"请先登录~~");
                }else {
                    showActionSheetDialog(items);
                }

                break;
            case R.id.personal://点击头像
                loginuser = MyApplication.getInstance().readLoginUser();
                if (loginuser==null){
                    startActivityForResult(new Intent(MainActivity.this,LoginActivity.class),234);
                }else {
                    intent = new Intent(MainActivity.this,ChangeInfoActivity.class);
                    intent.putExtra("login",loginuser);
                    startActivityForResult(intent,234);
//                    startActivityForResult(new Intent(MainActivity.this,ChangeActivity.class),234 );
                }
                break;
            case R.id.new_fenzu://新建分组
                loginuser = MyApplication.getInstance().readLoginUser();
                if (loginuser == null){
                    ToastUtils.shortToast(MainActivity.this,"请先登录~~");
                }else {
                    newClassifyDialog();
                }
                break;
            case R.id.mydinary://点击我的日记
//                title.setText("所有笔记");
                bmobUtils.getNote(loginuser,list,789,handler);
//                slidingMenu.closeMenu();
                break;
        }

    }

    /**
     * 新建分组提示框
     */
    private void newClassifyDialog() {

        final MyAlertDialog logDialog = new MyAlertDialog(this);
        logDialog.builder()
                .setTitle("新建")
                .setEditTextHint("请输入分组名称")
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                })
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String name = logDialog.getResult();
                        if (StringUtils.isEmpty(name)){
                            ToastUtils.shortToast(MainActivity.this,"分组名字不能为空");
                        }else {
                            dialog = ProgressDialog.show(MainActivity.this,null,"正在保存分组......");
                            saveClassify(name);
                        }
                    }
                })
                .show();
    }

    /**
     * 保存新建分组
     * @param name
     */
    private void saveClassify(String name) {
        if (classifyUser != null&&classifyUser.getName()!=null){
            List<String> nameList = classifyUser.getName();
            nameList.add(name);
            classifyUser.setName(nameList);
            bmobUtils.updateClassify(classifyUser,456,handler);
        }else {
            Classify classify = new Classify();
            classify.setId(loginuser.getId());
            List<String> nameList = new ArrayList<>();
            nameList.add(name);
            classify.setName(nameList);
            classifyUser = classify;
            bmobUtils.saveClassify(classify,456,handler);
        }

    }


    /**
     * 侧滑菜单的设置
     */
    private void initSlidingMenu() {
        //创建SlidingMenu对象
        slidingMenu = new SlidingMenu(this);
        //设置不用触摸屏幕模式打开侧滑菜单
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
        //设置侧滑菜单模式
        slidingMenu.setMode(SlidingMenu.LEFT);
        //设置侧滑菜单的显示宽度
        slidingMenu.setBehindOffset(getVmWidth() / 4);
        //将侧滑菜单加入到当前的界面中
        slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        //设置侧滑菜单的布局样式
        slidingMenu.setMenu(R.layout.sliding_left);

    }

    //头像选择对话框
    private void showActionSheetDialog(String[] items) {
        ActionSheet actionSheet = new ActionSheet(this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (int i = 0; i < items.length; i++) {
            actionSheet.addSheetItem(items[i], ActionSheet.SheetItemColor.Blue, MainActivity.this);
        }
        actionSheet.show();

    }

    @Override
    public void onClick(int which) {
        switch (which) {
            case TAKE_PHOTO:
                //拍照
                imageFile = ImageUploadUtil.createImageFile(ImageUploadUtil.CAMERA_SAVEDIR2, ImageUploadUtil.createImageName());
                startActivityForResult(ImageUploadUtil.intentImageCapture(imageFile), ImageUploadUtil.TAKE_PHOTO);
                break;
            case CHOOSE_PHOTO:
                //从相册选择
                startActivityForResult(ImageUtil.intentChooseImg(),
                        CHOOSE_PHOTO);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == 0) {
                    return;
                }
                //拍照
                ImageUtil.paizhaocreateImagefile(this, imageFile);
                if (imageFile == null) {
                    ToastUtils.shortToast(this, "图片太大无法上传");
                    return;
                }
                doSendThread();//上传图片
                break;
            case CHOOSE_PHOTO:
                //相册
                if (resultCode == 0) return;
                imageUri = data.getData();
                imageFile = MyApplication.getInstance().createimagefile(imageUri, getVmWidth(), getVmHeight());
                if (imageFile == null) {
                    ToastUtils.shortToast(this, "imageFile为空2");
                    return;
                }
                doSendThread();//上传图片
                break;
            case 123://添加日记之后
                loginuser = MyApplication.getInstance().readLoginUser();
                if (loginuser != null){
                    bmobUtils.getNote(loginuser,list,1,handler);
                }else {
                    setNotOnlineList();
                }

                break;
            case 234://登录之后或者编辑信息
                if (data !=null){
//                    if (data.getIntExtra("exit",0)==1){
//                        UserInfo userInfo = (UserInfo) data.getSerializableExtra("save");
//                        slidHead.setImageResource(R.mipmap.my_defalft_headpic);
//                        head.setImageResource(R.mipmap.my_defalft_headpic);
//                        name.setText("点击登录");
//                    }else {
                    Log.e("asdf","adfa");
                        UserInfo userInfo = (UserInfo) data.getSerializableExtra("save");
                        MyApplication.getInstance().saveUserInfo(userInfo);
                    Glide.with(MainActivity.this).load(userInfo.getHead().getFileUrl())
                            .error(R.drawable.chat_xe_icon2_03)
                            .into(slidHead);
                    Glide.with(MainActivity.this).load(userInfo.getHead().getFileUrl())
                            .error(R.drawable.chat_xe_icon2_03)
                            .into(head);
//                        ImageLoaderUtils.initImage(MainActivity.this,userInfo.getHead().getFileUrl(),slidHead,R.mipmap.my_defalft_headpic);
//                        ImageLoaderUtils.initImage(MainActivity.this,userInfo.getHead().getFileUrl(),head,R.mipmap.my_defalft_headpic);
                        name.setText(userInfo.getName());
                        bmobUtils.getNote(userInfo,list,1,handler);
//                    }

                }
                break;
        }

    }

    /**
     * 设置本地List显示
     */
    private void setNotOnlineList() {
        dbControl.query(list);
        Collections.reverse(list);
        count.setText(""+list.size()+"");
        if (list.size() == 0||list==null){
            emptyView.setNotify("快点写点日记吧~~~");
        }else {
            emptyView.setEmptyViewGone();
        }
        adapter.setList(list);
        adapter.notifyDataSetChanged();
    }

    /**
     * 上传头像
     */
    private void doSendThread() {
        dialog = ProgressDialog.show(this, null, "正在上传图片...");
//        Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getPath());
//        head.setImageBitmap(bitmap);
        BmobFile bmobFile = new BmobFile(imageFile);
        bmobUtils.upLoadImage(ImgList,bmobFile,SAVE_IMAGE_SUCCESS, handler);
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case SAVE_IMAGE_SUCCESS:
                    Intent intent = new Intent(MainActivity.this,WriteActivity.class);
                    intent.putExtra("file",ImgList.get(0));
                    intent.putExtra("has",1);
                    if (classifyUser != null){
                        if (classifyUser.getName()!=null){
                            intent.putExtra("hasClass",1);
                            intent.putExtra("classify", (Serializable) classifyUser.getName());
                        }
                    }
                    startActivityForResult(intent,123);
                    dialog.dismiss();
                    break;
                case 1://获取日记
                    allCount = list.size();
                    count.setText(""+allCount+"");
                    setNote();
                    //查询分组/
                    loginuser = MyApplication.getInstance().readLoginUser();
                    bmobUtils.getClassify(loginuser.getId(),2,handler);
                    break;
                case 2://获取分组
                    Bundle bundle = msg.getData();
                    Classify classify = (Classify) bundle.getSerializable("classify");
                    if (classify != null){
                        if (classify.getName().size()!=0){
                            classifyUser = classify;
                            //显示分组
                            classifyAdapter = new ClassifyAdapter(MainActivity.this,classifyUser.getName(),list);
                            sild_recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
                            sild_recyclerView.setAdapter(classifyAdapter);
                            classifyAdapter.setOnItemClickListener(onItemClickListener);
//                            classifyAdapter.setList(classifyUser.getName(),list);
//                            classifyAdapter.notifyDataSetChanged();
                        }
                    }
//                    dialog.dismiss();
                    break;
                case 456://新建分组
                    if (classifyAdapter == null){
                        classifyAdapter = new ClassifyAdapter(MainActivity.this,classifyUser.getName(),list);
                        sild_recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
                        sild_recyclerView.setAdapter(classifyAdapter);
                        classifyAdapter.setOnItemClickListener(onItemClickListener);
                    }else {
                        classifyAdapter.setList(classifyUser.getName(),list);
                        classifyAdapter.notifyDataSetChanged();
                    }
                    dialog.dismiss();
                    break;
                case 789:
                    setNote();
                    break;
                case 666:
//                    title.setText("所有笔记");
                    bmobUtils.getNote(loginuser,list,1,handler);
                    break;
            }
        }
    };


    @Override
    protected void onResume() {
        super.onResume();
        loginuser = MyApplication.getInstance().readLoginUser();
        if (loginuser != null){
            if (MyApplication.getInstance().isFirstLogin()){
                MyApplication.getInstance().updateIsFirstLogin(false);
                Glide.with(MainActivity.this).load(loginuser.getHead().getFileUrl())
                        .error(R.drawable.chat_xe_icon2_03)
                        .into(slidHead);
                Glide.with(MainActivity.this).load(loginuser.getHead().getFileUrl())
                        .error(R.drawable.chat_xe_icon2_03)
                        .into(head);
                name.setText(loginuser.getName());
                bmobUtils.getNote(loginuser,list,1,handler);
            }


        }
    }

    /**
     * 设置日记
     */
    private void setNote() {
        adapter.setOnline(true);
        recyclerView.setAdapter(adapter);
        Collections.reverse(list);

        if (list.size() == 0||list==null){
            emptyView.setNotify("快点写点日记吧~~~");
        }else {
            emptyView.setEmptyViewGone();
        }
        adapter.setList(list);
        adapter.notifyDataSetChanged();
    }

    /**
     * 分组的点击事件
     */
    private OnItemClickListener onItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(int position) {
//            title.setText(classifyUser.getName().get(position));
            bmobUtils.getNoteInfo(classifyUser.getName().get(position),loginuser.getId(),list,789,handler);
        }
    };
}

